package com.free.front.bf.product;


import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.deco.dao.domain.table.Variablespeed;
import com.deco.domain.vo.vin.VinSerFeedbackVo;
import com.deco.service.VariableSpeed.VarialbleSpeedService;
import com.deco.service.ti.TiDelcoLevelidModelService;
import com.deco.service.vin.VinSerFeedbackService;
import com.free.common.vo.ResultModel;
import com.free.ext.baidu.BaiduSdkContext;
import com.free.ext.baidu.BaiduSdkOcr;
import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.free.front.config.DecoConstants;
import com.free.front.util.SoapUtil;
import com.free.utils.RegexUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;

import java.util.*;


/**
 * <p>
 * 功能概述:
 * </p>
 * <p>
 * 功能详述:
 * </p>
 */
@Component
public class ProductVinSearchBf {
    /*========================================================================*
     *                         Public Fields (公共属性)
     *========================================================================*/

    /*========================================================================*
     *                         Private Fields (私有属性)
     *========================================================================*/

    private static final FreeLogger LOG = FreeLoggerFactory.getLogger(ProductVinSearchBf.class);

    @Autowired
    private ProductSearchBf prdSerBf;

    @Autowired
    private VinSerFeedbackService feedBackService;

    @Autowired
    private TiDelcoLevelidModelService delcoLevelidModelService;

    @Autowired
    VarialbleSpeedService variablespeedService;
    /*========================================================================*
     *                         Construct Methods (构造方法)
     *========================================================================*/

    /*========================================================================*
     *                         Public Methods (公有方法)
     *========================================================================*/

    public ResultModel analyzeVinCode(MultipartFile file){
        BaiduSdkOcr ocr = BaiduSdkContext.getSdkOcr(DecoConstants.DECO_BAIDU_OCR);
        if(file == null){
            return ResultModel.failure();
        }
        try {
            JSONObject json = ocr.vehicleLicense(file.getBytes());
            Map<String,Object> resMap = new HashMap<>();
            if(json != null){
                JSONArray array = json.names();
                if(array.toString().indexOf("words_result_num") >= 0){
                    Object obj = json.get("words_result_num");
                    if(obj != null){
                        if(Integer.parseInt(obj.toString())>0){
                            Object vinObj = json.getJSONObject("words_result").getJSONObject("车辆识别代号").get("words");
                            if(vinObj != null && StringUtils.isNotEmpty(vinObj.toString())){
                                resMap.put("type","1");
                                resMap.put("data",vinObj);
                                return ResultModel.success(resMap);
                            }
                        }
                    }
                }
            }
            json = ocr.analyze(file.getBytes());
            resMap.put("type","2");
            resMap.put("data",json.toString());
            return ResultModel.success(resMap);
        } catch (Exception e) {
            return ResultModel.failure();
        }
    }


    /*========================================================================*
     *                         Private Methods (私有方法)
     *========================================================================*/


    public ResultModel getByVinCode(String vin) {
        try{
            LOG.info("Vin码查询开始:{}", vin);
            Properties p = new Properties();
            try{
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("setting-web.properties");
                p.load(inputStream);
            } catch (IOException e1){
                LOG.info("Vin码Properties Loading 异常{}", e1);
            }

            String postUrl = p.getProperty("vin.checkAcWeb");
            String namespace = p.getProperty("vin.checkAcNamespace");
            String method = p.getProperty("vin.checkAcMethod");

            StringBuffer sb=new StringBuffer(
                    "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
            sb.append("<soap12:Body>");
            sb.append(" <" + method + " xmlns=\"http://tempuri.org/\">");
            sb.append("     <vin>" + vin + "</vin>");
            sb.append(" </" + method + ">");
            sb.append("</soap12:Body>");
            sb.append("</soap12:Envelope>");
            String soapXml = sb.toString();
            LOG.info("vin码查询调用XML信息：{}",soapXml);
            String result= SoapUtil.doPostSoap1_2(postUrl, soapXml, StringUtils.EMPTY);
            //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><GetJZTWCXInfoByVINResponse xmlns=\"http://tempuri.org/\"><GetJZTWCXInfoByVINResult>[{\"LevelID\":\"QB007784\",\"CJ\":\"\\u4E0A\\u6D77\\u901A\\u7528\",\"PP\":\"\\u522B\\u514B\",\"CXI\":\"\\u541B\\u5A01\",\"CX\":\"\\u541B\\u5A01\",\"XSMC\":\"2.0 \\u624B\\u81EA\\u4E00\\u4F53 \\u8212\\u9002\\u7248\",\"NK\":\"2012\",\"SSNF\":\"2012\",\"SCNF\":\"2012\",\"TCNF\":\"2013\",\"SCZT\":\"\\u505C\\u4EA7\",\"GB\":\"\\u4E2D\\u56FD\",\"GCHZJK\":\"\\u5408\\u8D44\",\"PFBZ\":\"\\u56FD4\",\"CLLX\":\"\\u8F7F\\u8F66\",\"ZDJG\":\"18.59\",\"FDJXH\":\"LTD\",\"PL\":\"2\",\"JQXS\":\"\\u81EA\\u7136\\u5438\\u6C14\",\"RYLX\":\"\\u6C7D\\u6CB9\",\"RYBH\":\"93#\",\"BSQLX\":\"\\u81EA\\u52A8\",\"BSQMS\":\"\\u624B\\u81EA\\u4E00\\u4F53\\u53D8\\u901F\\u5668(AMT)\",\"CSXS\":\"\\u4E09\\u53A2\",\"QDXS\":\"\\u524D\\u7F6E\\u524D\\u9A71\",\"DWS\":\"6\"}]</GetJZTWCXInfoByVINResult></GetJZTWCXInfoByVINResponse></soap:Body></soap:Envelope>";
            LOG.info("vin码查询调用XML结果:{}",result);
            ResultModel resModel = jsonToMap(result);
            if(!resModel.isSuccess()){
                return resModel;
            }
            List<Map> lst = (List<Map>)resModel.getData();
            List<String> levelIds = new ArrayList<>();
            lst.forEach(x->{
                levelIds.add(x.get("LevelID").toString());
            });
            String vehcleInfo = delcoLevelidModelService.getVehicleNoByLevelId(levelIds);
            LOG.info("vin码查询，汽车编号{}",vehcleInfo);
            return ResultModel.success(prdSerBf.getPartDetAndCarInfo(vehcleInfo));
        }
        catch (Exception e) {
             LOG.info("调用WebService出错：{}" ,e);
            return ResultModel.failure();
        }
    }


    /**
     * 变速箱油vim码查询
     * @param vin
     * @return
     */
    public ResultModel getByVarialbleVinCode(String vin) {
        try{
            LOG.info("Vin码查询开始:{}", vin);
            Properties p = new Properties();
            try{
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("setting-web.properties");
                p.load(inputStream);
            } catch (IOException e1){
                LOG.info("Vin码Properties Loading 异常{}", e1);
            }

            String postUrl = p.getProperty("vin.checkAcWeb");
            String namespace = p.getProperty("vin.checkAcNamespace");
            String method = p.getProperty("vin.checkAcMethod");

            StringBuffer sb=new StringBuffer(
                    "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
            sb.append("<soap12:Body>");
            sb.append(" <" + method + " xmlns=\"http://tempuri.org/\">");
            sb.append("     <vin>" + vin + "</vin>");
            sb.append(" </" + method + ">");
            sb.append("</soap12:Body>");
            sb.append("</soap12:Envelope>");
            String soapXml = sb.toString();
            LOG.info("vin码查询调用XML信息：{}",soapXml);
            String result= SoapUtil.doPostSoap1_2(postUrl, soapXml, StringUtils.EMPTY);
            //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><GetJZTWCXInfoByVINResponse xmlns=\"http://tempuri.org/\"><GetJZTWCXInfoByVINResult>[{\"LevelID\":\"QB007784\",\"CJ\":\"\\u4E0A\\u6D77\\u901A\\u7528\",\"PP\":\"\\u522B\\u514B\",\"CXI\":\"\\u541B\\u5A01\",\"CX\":\"\\u541B\\u5A01\",\"XSMC\":\"2.0 \\u624B\\u81EA\\u4E00\\u4F53 \\u8212\\u9002\\u7248\",\"NK\":\"2012\",\"SSNF\":\"2012\",\"SCNF\":\"2012\",\"TCNF\":\"2013\",\"SCZT\":\"\\u505C\\u4EA7\",\"GB\":\"\\u4E2D\\u56FD\",\"GCHZJK\":\"\\u5408\\u8D44\",\"PFBZ\":\"\\u56FD4\",\"CLLX\":\"\\u8F7F\\u8F66\",\"ZDJG\":\"18.59\",\"FDJXH\":\"LTD\",\"PL\":\"2\",\"JQXS\":\"\\u81EA\\u7136\\u5438\\u6C14\",\"RYLX\":\"\\u6C7D\\u6CB9\",\"RYBH\":\"93#\",\"BSQLX\":\"\\u81EA\\u52A8\",\"BSQMS\":\"\\u624B\\u81EA\\u4E00\\u4F53\\u53D8\\u901F\\u5668(AMT)\",\"CSXS\":\"\\u4E09\\u53A2\",\"QDXS\":\"\\u524D\\u7F6E\\u524D\\u9A71\",\"DWS\":\"6\"}]</GetJZTWCXInfoByVINResult></GetJZTWCXInfoByVINResponse></soap:Body></soap:Envelope>";
            LOG.info("vin码查询调用XML结果:{}",result);
            ResultModel resModel = jsonToMap(result);
            if(!resModel.isSuccess()){
                return resModel;
            }
            List<Map> lst = (List<Map>)resModel.getData();
            List<String> levelIds = new ArrayList<>();
            lst.forEach(x->{
                levelIds.add(x.get("LevelID").toString());
            });
            LOG.info("vin查询汽车LEVELID:{}",StringUtils.join(levelIds,","));
            //得到力洋id
            String levelId = delcoLevelidModelService.getLevelId(levelIds);
            //通过力洋id拿到谨思Vehicle ID二级
            List<Variablespeed> list = variablespeedService.getByLevelId(levelId);
            String tid = list.get(0).getTid();
            //通过力洋id和二级id查询车型数据
            return ResultModel.success(variablespeedService.getByvehcleId(levelId,tid));
        }
        catch (Exception e) {
            LOG.info("调用WebService出错：{}" ,e);
            return ResultModel.failure();
        }
    }

     /**
     * 保存内容到反馈表
     * @param feedBackVo
     * @return
     */
    public ResultModel saveIntoFeedBack(VinSerFeedbackVo feedBackVo){
        if(StringUtils.isEmpty(feedBackVo.getUsername())){
            return ResultModel.failure(false,"姓名不能为空！");
        }
        if(StringUtils.isEmpty(feedBackVo.getEmail())){
            return ResultModel.failure(false,"邮箱不能为空！");
        }
        //邮箱正则
        String regex  = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        boolean flag = feedBackVo.getEmail().matches(regex);
        if(!flag){
            return ResultModel.failure(false,"邮箱格式不对！");
        }
        if(StringUtils.isNotEmpty(feedBackVo.getPhone()) && !RegexUtils.isMobileSimple(feedBackVo.getPhone())){
            return ResultModel.failure(false,"手机号码不正确！");
        }
//        if(StringUtils.isEmpty(feedBackVo.getModel())){
//            return ResultModel.failure(false,"您的车型不能为空！");
//        }
//        if(StringUtils.isEmpty(feedBackVo.getVol())){
//            return ResultModel.failure(false,"车型排量不能为空！");
//        }
//        if(StringUtils.isEmpty(feedBackVo.getGeneration())){
//            return ResultModel.failure(false,"车型年款不能为空！");
//        }
        if(feedBackVo.getFeedtype()==null){
            return ResultModel.failure(false,"反馈类型不能为空！");
        }
        if(feedBackVo.getFeedtype()<0||feedBackVo.getFeedtype()>3){
            return ResultModel.failure(false,"选择反馈类型错误！");
        }
        feedBackVo.setFeedtime(new Date());
        feedBackVo = feedBackService.insert(feedBackVo);
        return ResultModel.success(feedBackVo);
    }


    private ResultModel jsonToMap(String result){
        if(StringUtils.isEmpty(result)){
            return ResultModel.failure();
        }
        int start = result.indexOf("<GetJZTWCXInfoByVINResult>");
        if(start < 0){
            return ResultModel.failure();
        }
        start = start + 26;
        int end = result.indexOf("</GetJZTWCXInfoByVINResult>");
        String content = result.substring(start,end);
        List<Map> maps = JSON.parseArray(content ,Map.class);
        return ResultModel.success(maps);
    }

    public static void main(String[] args) throws Exception {
        File f = new File("C:\\Users\\Administrator\\Desktop\\0585f81ccbda4a082c155c323701857.png");
        FileInputStream fis = new FileInputStream(f);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1000];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        HashMap<String,String> defaultOptions = new HashMap<String,String>();
        defaultOptions.put("language_type", "CHN_ENG");
        defaultOptions.put("detect_direction", "true");
        defaultOptions.put("detect_language", "true");
        defaultOptions.put("accuracy", "normal");
        defaultOptions.put("probability", "true");
        byte[] buffer = bos.toByteArray();
        AipOcr ocr = new AipOcr("15138148","Xh68uQ7SM2kDagkAmQPituo1","k12z1r0YKuyL4Q8BbT8yCm9AtyNHg0bb");
        JSONObject jsonObj = ocr.vehicleLicense(buffer,defaultOptions);
        //jsonObj.getJSONArray()
        System.out.println(jsonObj.toString(2));
        //jsonObj.get("");
//        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><GetJZTWCXInfoByVINResponse xmlns=\"http://tempuri.org/\"><GetJZTWCXInfoByVINResult>[{\"LevelID\":\"QB024319\",\"CJ\":\"\u4E0A\u6D77\u901A\u7528\",\"PP\":\"\u522B\u514B\",\"CXI\":\"GL8\",\"CX\":\"GL8 \u8C6A\u534E\u5546\u52A1\u8F66\",\"XSMC\":\"2.4 \u624B\u81EA\u4E00\u4F53 CT \u8212\u9002\u7248\",\"NK\":\"2014\",\"SSNF\":\"2014\",\"SCNF\":\"2015\",\"TCNF\":\"2016\",\"SCZT\":\"\u505C\u4EA7\",\"GB\":\"\u4E2D\u56FD\",\"GCHZJK\":\"\u5408\u8D44\",\"PFBZ\":\"\u56FD5\",\"CLLX\":\"MPV\",\"ZDJG\":\"28.99\",\"FDJXH\":\"LAF\",\"PL\":\"2.4\",\"JQXS\":\"\u81EA\u7136\u5438\u6C14\",\"RYLX\":\"\u6C7D\u6CB9\",\"RYBH\":\"93#\",\"BSQLX\":\"\u81EA\u52A8\",\"BSQMS\":\"\u624B\u81EA\u4E00\u4F53\u53D8\u901F\u5668(AMT)\",\"CSXS\":\"\u4E24\u53A2\",\"QDXS\":\"\u524D\u7F6E\u524D\u9A71\",\"DWS\":\"6\"},{\"LevelID\":\"QB024320\",\"CJ\":\"\u4E0A\u6D77\u901A\u7528\",\"PP\":\"\u522B\u514B\",\"CXI\":\"GL8\",\"CX\":\"GL8 \u8C6A\u534E\u5546\u52A1\u8F66\",\"XSMC\":\"2.4 \u624B\u81EA\u4E00\u4F53 LT \u884C\u653F\u7248\",\"NK\":\"2014\",\"SSNF\":\"2014\",\"SCNF\":\"2015\",\"TCNF\":\"2016\",\"SCZT\":\"\u505C\u4EA7\",\"GB\":\"\u4E2D\u56FD\",\"GCHZJK\":\"\u5408\u8D44\",\"PFBZ\":\"\u56FD5\",\"CLLX\":\"MPV\",\"ZDJG\":\"32.99\",\"FDJXH\":\"LAF\",\"PL\":\"2.4\",\"JQXS\":\"\u81EA\u7136\u5438\u6C14\",\"RYLX\":\"\u6C7D\u6CB9\",\"RYBH\":\"93#\",\"BSQLX\":\"\u81EA\u52A8\",\"BSQMS\":\"\u624B\u81EA\u4E00\u4F53\u53D8\u901F\u5668(AMT)\",\"CSXS\":\"\u4E24\u53A2\",\"QDXS\":\"\u524D\u7F6E\u524D\u9A71\",\"DWS\":\"6\"},{\"LevelID\":\"QB025861\",\"CJ\":\"\u4E0A\u6D77\u901A\u7528\",\"PP\":\"\u522B\u514B\",\"CXI\":\"GL8\",\"CX\":\"GL8 \u8C6A\u534E\u5546\u52A1\u8F66\",\"XSMC\":\"2.4 \u624B\u81EA\u4E00\u4F53 \u5C0A\u4EAB\u7248\",\"NK\":\"2015\",\"SSNF\":\"2015\",\"SCNF\":\"2015\",\"TCNF\":\"2016\",\"SCZT\":\"\u505C\u4EA7\",\"GB\":\"\u4E2D\u56FD\",\"GCHZJK\":\"\u5408\u8D44\",\"PFBZ\":\"\u56FD5\",\"CLLX\":\"MPV\",\"ZDJG\":\"30.99\",\"FDJXH\":\"LAF\",\"PL\":\"2.4\",\"JQXS\":\"\u81EA\u7136\u5438\u6C14\",\"RYLX\":\"\u6C7D\u6CB9\",\"RYBH\":\"93#\",\"BSQLX\":\"\u81EA\u52A8\",\"BSQMS\":\"\u624B\u81EA\u4E00\u4F53\u53D8\u901F\u5668(AMT)\",\"CSXS\":\"\u4E24\u53A2\",\"QDXS\":\"\u524D\u7F6E\u524D\u9A71\",\"DWS\":\"6\"}]</GetJZTWCXInfoByVINResult></GetJZTWCXInfoByVINResponse></soap:Body></soap:Envelope>";
//        int start = xml.indexOf("<GetJZTWCXInfoByVINResult>") + 26;
//        int end = xml.indexOf("</GetJZTWCXInfoByVINResult>");
//        String res = xml.substring(start,end);
//        List<Map> ress = JSON.parseArray(res,Map.class);
//
//        System.out.println(res);




    }

}
